home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Objects / stringobject.c < prev    next >
Encoding:
C/C++ Source or Header  |  2000-09-10  |  61.8 KB  |  2,830 lines

  1. /* String object implementation */
  2.  
  3. #include "Python.h"
  4.  
  5. #include "mymath.h"
  6. #include <ctype.h>
  7. #include "protos/stringobject.h"
  8.  
  9. #ifdef COUNT_ALLOCS
  10. int null_strings, one_strings;
  11. #endif
  12.  
  13. #ifdef HAVE_LIMITS_H
  14. #include <limits.h>
  15. #else
  16. #ifndef UCHAR_MAX
  17. #define UCHAR_MAX 255
  18. #endif
  19. #endif
  20.  
  21. static PyStringObject *characters[UCHAR_MAX + 1];
  22. #ifndef DONT_SHARE_SHORT_STRINGS
  23. static PyStringObject *nullstring;
  24. #endif
  25.  
  26. /*
  27.    Newsizedstringobject() and newstringobject() try in certain cases
  28.    to share string objects.  When the size of the string is zero,
  29.    these routines always return a pointer to the same string object;
  30.    when the size is one, they return a pointer to an already existing
  31.    object if the contents of the string is known.  For
  32.    newstringobject() this is always the case, for
  33.    newsizedstringobject() this is the case when the first argument in
  34.    not NULL.
  35.    A common practice to allocate a string and then fill it in or
  36.    change it must be done carefully.  It is only allowed to change the
  37.    contents of the string if the obect was gotten from
  38.    newsizedstringobject() with a NULL first argument, because in the
  39.    future these routines may try to do even more sharing of objects.
  40. */
  41. PyObject *
  42. PyString_FromStringAndSize(str, size)
  43.     const char *str;
  44.     int size;
  45. {
  46.     register PyStringObject *op;
  47. #ifndef DONT_SHARE_SHORT_STRINGS
  48.     if (size == 0 && (op = nullstring) != NULL) {
  49. #ifdef COUNT_ALLOCS
  50.         null_strings++;
  51. #endif
  52.         Py_INCREF(op);
  53.         return (PyObject *)op;
  54.     }
  55.     if (size == 1 && str != NULL &&
  56.         (op = characters[*str & UCHAR_MAX]) != NULL)
  57.     {
  58. #ifdef COUNT_ALLOCS
  59.         one_strings++;
  60. #endif
  61.         Py_INCREF(op);
  62.         return (PyObject *)op;
  63.     }
  64. #endif /* DONT_SHARE_SHORT_STRINGS */
  65.  
  66.     /* PyObject_NewVar is inlined */
  67.     op = (PyStringObject *)
  68.         PyObject_MALLOC(sizeof(PyStringObject) + size * sizeof(char));
  69.     if (op == NULL)
  70.         return PyErr_NoMemory();
  71.     PyObject_INIT_VAR(op, &PyString_Type, size);
  72. #ifdef CACHE_HASH
  73.     op->ob_shash = -1;
  74. #endif
  75. #ifdef INTERN_STRINGS
  76.     op->ob_sinterned = NULL;
  77. #endif
  78.     if (str != NULL)
  79.         memcpy(op->ob_sval, str, size);
  80.     op->ob_sval[size] = '\0';
  81. #ifndef DONT_SHARE_SHORT_STRINGS
  82.     if (size == 0) {
  83.         nullstring = op;
  84.         Py_INCREF(op);
  85.     } else if (size == 1 && str != NULL) {
  86.         characters[*str & UCHAR_MAX] = op;
  87.         Py_INCREF(op);
  88.     }
  89. #endif
  90.     return (PyObject *) op;
  91. }
  92.  
  93. PyObject *
  94. PyString_FromString(str)
  95.     const char *str;
  96. {
  97.     register unsigned int size = strlen(str);
  98.     register PyStringObject *op;
  99. #ifndef DONT_SHARE_SHORT_STRINGS
  100.     if (size == 0 && (op = nullstring) != NULL) {
  101. #ifdef COUNT_ALLOCS
  102.         null_strings++;
  103. #endif
  104.         Py_INCREF(op);
  105.         return (PyObject *)op;
  106.     }
  107.     if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
  108. #ifdef COUNT_ALLOCS
  109.         one_strings++;
  110. #endif
  111.         Py_INCREF(op);
  112.         return (PyObject *)op;
  113.     }
  114. #endif /* DONT_SHARE_SHORT_STRINGS */
  115.  
  116.     /* PyObject_NewVar is inlined */
  117.     op = (PyStringObject *)
  118.         PyObject_MALLOC(sizeof(PyStringObject) + size * sizeof(char));
  119.     if (op == NULL)
  120.         return PyErr_NoMemory();
  121.     PyObject_INIT_VAR(op, &PyString_Type, size);
  122. #ifdef CACHE_HASH
  123.     op->ob_shash = -1;
  124. #endif
  125. #ifdef INTERN_STRINGS
  126.     op->ob_sinterned = NULL;
  127. #endif
  128.     strcpy(op->ob_sval, str);
  129. #ifndef DONT_SHARE_SHORT_STRINGS
  130.     if (size == 0) {
  131.         nullstring = op;
  132.         Py_INCREF(op);
  133.     } else if (size == 1) {
  134.         characters[*str & UCHAR_MAX] = op;
  135.         Py_INCREF(op);
  136.     }
  137. #endif
  138.     return (PyObject *) op;
  139. }
  140.  
  141. static void
  142. string_dealloc(op)
  143.     PyObject *op;
  144. {
  145.     PyObject_DEL(op);
  146. }
  147.  
  148. int
  149. PyString_Size(op)
  150.     register PyObject *op;
  151. {
  152.     if (!PyString_Check(op)) {
  153.         PyErr_BadInternalCall();
  154.         return -1;
  155.     }
  156.     return ((PyStringObject *)op) -> ob_size;
  157. }
  158.  
  159. /*const*/ char *
  160. PyString_AsString(op)
  161.     register PyObject *op;
  162. {
  163.     if (!PyString_Check(op)) {
  164.         PyErr_BadInternalCall();
  165.         return NULL;
  166.     }
  167.     return ((PyStringObject *)op) -> ob_sval;
  168. }
  169.  
  170. /* Methods */
  171.  
  172. static int
  173. string_print(op, fp, flags)
  174.     PyStringObject *op;
  175.     FILE *fp;
  176.     int flags;
  177. {
  178.     int i;
  179.     char c;
  180.     int quote;
  181.     /* XXX Ought to check for interrupts when writing long strings */
  182.     if (flags & Py_PRINT_RAW) {
  183.         fwrite(op->ob_sval, 1, (int) op->ob_size, fp);
  184.         return 0;
  185.     }
  186.  
  187.     /* figure out which quote to use; single is prefered */
  188.     quote = '\'';
  189.     if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  190.         quote = '"';
  191.  
  192.     fputc(quote, fp);
  193.     for (i = 0; i < op->ob_size; i++) {
  194.         c = op->ob_sval[i];
  195.         if (c == quote || c == '\\')
  196.             fprintf(fp, "\\%c", c);
  197.         else if (c < ' ' || c >= 0177)
  198.             fprintf(fp, "\\%03o", c & 0377);
  199.         else
  200.             fputc(c, fp);
  201.     }
  202.     fputc(quote, fp);
  203.     return 0;
  204. }
  205.  
  206. static PyObject *
  207. string_repr(op)
  208.     register PyStringObject *op;
  209. {
  210.     /* XXX overflow? */
  211.     int newsize = 2 + 4 * op->ob_size * sizeof(char);
  212.     PyObject *v = PyString_FromStringAndSize((char *)NULL, newsize);
  213.     if (v == NULL) {
  214.         return NULL;
  215.     }
  216.     else {
  217.         register int i;
  218.         register char c;
  219.         register char *p;
  220.         int quote;
  221.  
  222.         /* figure out which quote to use; single is prefered */
  223.         quote = '\'';
  224.         if (strchr(op->ob_sval, '\'') && !strchr(op->ob_sval, '"'))
  225.             quote = '"';
  226.  
  227.         p = ((PyStringObject *)v)->ob_sval;
  228.         *p++ = quote;
  229.         for (i = 0; i < op->ob_size; i++) {
  230.             c = op->ob_sval[i];
  231.             if (c == quote || c == '\\')
  232.                 *p++ = '\\', *p++ = c;
  233.             else if (c < ' ' || c >= 0177) {
  234.                 sprintf(p, "\\%03o", c & 0377);
  235.                 while (*p != '\0')
  236.                     p++;
  237.             }
  238.             else
  239.                 *p++ = c;
  240.         }
  241.         *p++ = quote;
  242.         *p = '\0';
  243.         _PyString_Resize(
  244.             &v, (int) (p - ((PyStringObject *)v)->ob_sval));
  245.         return v;
  246.     }
  247. }
  248.  
  249. static int
  250. string_length(a)
  251.     PyStringObject *a;
  252. {
  253.     return a->ob_size;
  254. }
  255.  
  256. static PyObject *
  257. string_concat(a, bb)
  258.     register PyStringObject *a;
  259.     register PyObject *bb;
  260. {
  261.     register unsigned int size;
  262.     register PyStringObject *op;
  263.     if (!PyString_Check(bb)) {
  264.         if (PyUnicode_Check(bb))
  265.             return PyUnicode_Concat((PyObject *)a, bb);
  266.         PyErr_BadArgument();
  267.         return NULL;
  268.     }
  269. #define b ((PyStringObject *)bb)
  270.     /* Optimize cases with empty left or right operand */
  271.     if (a->ob_size == 0) {
  272.         Py_INCREF(bb);
  273.         return bb;
  274.     }
  275.     if (b->ob_size == 0) {
  276.         Py_INCREF(a);
  277.         return (PyObject *)a;
  278.     }
  279.     size = a->ob_size + b->ob_size;
  280.     /* PyObject_NewVar is inlined */
  281.     op = (PyStringObject *)
  282.         PyObject_MALLOC(sizeof(PyStringObject) + size * sizeof(char));
  283.     if (op == NULL)
  284.         return PyErr_NoMemory();
  285.     PyObject_INIT_VAR(op, &PyString_Type, size);
  286. #ifdef CACHE_HASH
  287.     op->ob_shash = -1;
  288. #endif
  289. #ifdef INTERN_STRINGS
  290.     op->ob_sinterned = NULL;
  291. #endif
  292.     memcpy(op->ob_sval, a->ob_sval, (int) a->ob_size);
  293.     memcpy(op->ob_sval + a->ob_size, b->ob_sval, (int) b->ob_size);
  294.     op->ob_sval[size] = '\0';
  295.     return (PyObject *) op;
  296. #undef b
  297. }
  298.  
  299. static PyObject *
  300. string_repeat(a, n)
  301.     register PyStringObject *a;
  302.     register int n;
  303. {
  304.     register int i;
  305.     register int size;
  306.     register PyStringObject *op;
  307.     if (n < 0)
  308.         n = 0;
  309.     size = a->ob_size * n;
  310.     if (size == a->ob_size) {
  311.         Py_INCREF(a);
  312.         return (PyObject *)a;
  313.     }
  314.     /* PyObject_NewVar is inlined */
  315.     op = (PyStringObject *)
  316.         PyObject_MALLOC(sizeof(PyStringObject) + size * sizeof(char));
  317.     if (op == NULL)
  318.         return PyErr_NoMemory();
  319.     PyObject_INIT_VAR(op, &PyString_Type, size);
  320. #ifdef CACHE_HASH
  321.     op->ob_shash = -1;
  322. #endif
  323. #ifdef INTERN_STRINGS
  324.     op->ob_sinterned = NULL;
  325. #endif
  326.     for (i = 0; i < size; i += a->ob_size)
  327.         memcpy(op->ob_sval+i, a->ob_sval, (int) a->ob_size);
  328.     op->ob_sval[size] = '\0';
  329.     return (PyObject *) op;
  330. }
  331.  
  332. /* String slice a[i:j] consists of characters a[i] ... a[j-1] */
  333.  
  334. static PyObject *
  335. string_slice(a, i, j)
  336.     register PyStringObject *a;
  337.     register int i, j; /* May be negative! */
  338. {
  339.     if (i < 0)
  340.         i = 0;
  341.     if (j < 0)
  342.         j = 0; /* Avoid signed/unsigned bug in next line */
  343.     if (j > a->ob_size)
  344.         j = a->ob_size;
  345.     if (i == 0 && j == a->ob_size) { /* It's the same as a */
  346.         Py_INCREF(a);
  347.         return (PyObject *)a;
  348.     }
  349.     if (j < i)
  350.         j = i;
  351.     return PyString_FromStringAndSize(a->ob_sval + i, (int) (j-i));
  352. }
  353.  
  354. static int
  355. string_contains(a, el)
  356. PyObject *a, *el;
  357. {
  358.     register char *s, *end;
  359.     register char c;
  360.     if (PyUnicode_Check(el))
  361.         return PyUnicode_Contains(a, el);
  362.     if (!PyString_Check(el) || PyString_Size(el) != 1) {
  363.         PyErr_SetString(PyExc_TypeError,
  364.                 "string member test needs char left operand");
  365.         return -1;
  366.     }
  367.     c = PyString_AsString(el)[0];
  368.     s = PyString_AsString(a);
  369.     end = s + PyString_Size(a);
  370.     while (s < end) {
  371.         if (c == *s++)
  372.             return 1;
  373.     }
  374.     return 0;
  375. }
  376.  
  377. static PyObject *
  378. string_item(a, i)
  379.     PyStringObject *a;
  380.     register int i;
  381. {
  382.     int c;
  383.     PyObject *v;
  384.     if (i < 0 || i >= a->ob_size) {
  385.         PyErr_SetString(PyExc_IndexError, "string index out of range");
  386.         return NULL;
  387.     }
  388.     c = a->ob_sval[i] & UCHAR_MAX;
  389.     v = (PyObject *) characters[c];
  390. #ifdef COUNT_ALLOCS
  391.     if (v != NULL)
  392.         one_strings++;
  393. #endif
  394.     if (v == NULL) {
  395.         v = PyString_FromStringAndSize((char *)NULL, 1);
  396.         if (v == NULL)
  397.             return NULL;
  398.         characters[c] = (PyStringObject *) v;
  399.         ((PyStringObject *)v)->ob_sval[0] = c;
  400.     }
  401.     Py_INCREF(v);
  402.     return v;
  403. }
  404.  
  405. static int
  406. string_compare(a, b)
  407.     PyStringObject *a, *b;
  408. {
  409.     int len_a = a->ob_size, len_b = b->ob_size;
  410.     int min_len = (len_a < len_b) ? len_a : len_b;
  411.     int cmp;
  412.     if (min_len > 0) {
  413.         cmp = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
  414.         if (cmp == 0)
  415.             cmp = memcmp(a->ob_sval, b->ob_sval, min_len);
  416.         if (cmp != 0)
  417.             return cmp;
  418.     }
  419.     return (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
  420. }
  421.  
  422. static long
  423. string_hash(a)
  424.     PyStringObject *a;
  425. {
  426.     register int len;
  427.     register unsigned char *p;
  428.     register long x;
  429.  
  430. #ifdef CACHE_HASH
  431.     if (a->ob_shash != -1)
  432.         return a->ob_shash;
  433. #ifdef INTERN_STRINGS
  434.     if (a->ob_sinterned != NULL)
  435.         return (a->ob_shash =
  436.             ((PyStringObject *)(a->ob_sinterned))->ob_shash);
  437. #endif
  438. #endif
  439.     len = a->ob_size;
  440.     p = (unsigned char *) a->ob_sval;
  441.     x = *p << 7;
  442.     while (--len >= 0)
  443.         x = (1000003*x) ^ *p++;
  444.     x ^= a->ob_size;
  445.     if (x == -1)
  446.         x = -2;
  447. #ifdef CACHE_HASH
  448.     a->ob_shash = x;
  449. #endif
  450.     return x;
  451. }
  452.  
  453. static int
  454. string_buffer_getreadbuf(self, index, ptr)
  455.     PyStringObject *self;
  456.     int index;
  457.     const void **ptr;
  458. {
  459.     if ( index != 0 ) {
  460.         PyErr_SetString(PyExc_SystemError,
  461.                 "accessing non-existent string segment");
  462.         return -1;
  463.     }
  464.     *ptr = (void *)self->ob_sval;
  465.     return self->ob_size;
  466. }
  467.  
  468. static int
  469. string_buffer_getwritebuf(self, index, ptr)
  470.     PyStringObject *self;
  471.     int index;
  472.     const void **ptr;
  473. {
  474.     PyErr_SetString(PyExc_TypeError,
  475.             "Cannot use string as modifiable buffer");
  476.     return -1;
  477. }
  478.  
  479. static int
  480. string_buffer_getsegcount(self, lenp)
  481.     PyStringObject *self;
  482.     int *lenp;
  483. {
  484.     if ( lenp )
  485.         *lenp = self->ob_size;
  486.     return 1;
  487. }
  488.  
  489. static int
  490. string_buffer_getcharbuf(self, index, ptr)
  491.     PyStringObject *self;
  492.     int index;
  493.     const char **ptr;
  494. {
  495.     if ( index != 0 ) {
  496.         PyErr_SetString(PyExc_SystemError,
  497.                 "accessing non-existent string segment");
  498.         return -1;
  499.     }
  500.     *ptr = self->ob_sval;
  501.     return self->ob_size;
  502. }
  503.  
  504. static PySequenceMethods string_as_sequence = {
  505.     (inquiry)string_length, /*sq_length*/
  506.     (binaryfunc)string_concat, /*sq_concat*/
  507.     (intargfunc)string_repeat, /*sq_repeat*/
  508.     (intargfunc)string_item, /*sq_item*/
  509.     (intintargfunc)string_slice, /*sq_slice*/
  510.     0,        /*sq_ass_item*/
  511.     0,        /*sq_ass_slice*/
  512.     (objobjproc)string_contains /*sq_contains*/
  513. };
  514.  
  515. static PyBufferProcs string_as_buffer = {
  516.     (getreadbufferproc)string_buffer_getreadbuf,
  517.     (getwritebufferproc)string_buffer_getwritebuf,
  518.     (getsegcountproc)string_buffer_getsegcount,
  519.     (getcharbufferproc)string_buffer_getcharbuf,
  520. };
  521.  
  522.  
  523.  
  524. #define LEFTSTRIP 0
  525. #define RIGHTSTRIP 1
  526. #define BOTHSTRIP 2
  527.  
  528.  
  529. static PyObject *
  530. split_whitespace(s, len, maxsplit)
  531.     char *s;
  532.     int len;
  533.     int maxsplit;
  534. {
  535.     int i, j, err;
  536.     PyObject* item;
  537.     PyObject *list = PyList_New(0);
  538.  
  539.     if (list == NULL)
  540.         return NULL;
  541.  
  542.     for (i = j = 0; i < len; ) {
  543.         while (i < len && isspace(Py_CHARMASK(s[i])))
  544.             i++;
  545.         j = i;
  546.         while (i < len && !isspace(Py_CHARMASK(s[i])))
  547.             i++;
  548.         if (j < i) {
  549.             if (maxsplit-- <= 0)
  550.                 break;
  551.             item = PyString_FromStringAndSize(s+j, (int)(i-j));
  552.             if (item == NULL)
  553.                 goto finally;
  554.             err = PyList_Append(list, item);
  555.             Py_DECREF(item);
  556.             if (err < 0)
  557.                 goto finally;
  558.             while (i < len && isspace(Py_CHARMASK(s[i])))
  559.                 i++;
  560.             j = i;
  561.         }
  562.     }
  563.     if (j < len) {
  564.         item = PyString_FromStringAndSize(s+j, (int)(len - j));
  565.         if (item == NULL)
  566.             goto finally;
  567.         err = PyList_Append(list, item);
  568.         Py_DECREF(item);
  569.         if (err < 0)
  570.             goto finally;
  571.     }
  572.     return list;
  573.   finally:
  574.     Py_DECREF(list);
  575.     return NULL;
  576. }
  577.  
  578.  
  579. static char split__doc__[] =
  580. "S.split([sep [,maxsplit]]) -> list of strings\n\
  581. \n\
  582. Return a list of the words in the string S, using sep as the\n\
  583. delimiter string.  If maxsplit is given, at most maxsplit\n\
  584. splits are done. If sep is not specified, any whitespace string\n\
  585. is a separator.";
  586.  
  587. static PyObject *
  588. string_split(self, args)
  589.     PyStringObject *self;
  590.     PyObject *args;
  591. {
  592.     int len = PyString_GET_SIZE(self), n, i, j, err;
  593.     int maxsplit = -1;
  594.     const char *s = PyString_AS_STRING(self), *sub;
  595.     PyObject *list, *item, *subobj = Py_None;
  596.  
  597.     if (!PyArg_ParseTuple(args, "|Oi:split", &subobj, &maxsplit))
  598.         return NULL;
  599.     if (maxsplit < 0)
  600.         maxsplit = INT_MAX;
  601.     if (subobj == Py_None)
  602.         return split_whitespace(s, len, maxsplit);
  603.     if (PyString_Check(subobj)) {
  604.         sub = PyString_AS_STRING(subobj);
  605.         n = PyString_GET_SIZE(subobj);
  606.     }
  607.     else if (PyUnicode_Check(subobj))
  608.         return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
  609.     else if (PyObject_AsCharBuffer(subobj, &sub, &n))
  610.         return NULL;
  611.     if (n == 0) {
  612.         PyErr_SetString(PyExc_ValueError, "empty separator");
  613.         return NULL;
  614.     }
  615.  
  616.     list = PyList_New(0);
  617.     if (list == NULL)
  618.         return NULL;
  619.  
  620.     i = j = 0;
  621.     while (i+n <= len) {
  622.         if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
  623.             if (maxsplit-- <= 0)
  624.                 break;
  625.             item = PyString_FromStringAndSize(s+j, (int)(i-j));
  626.             if (item == NULL)
  627.                 goto fail;
  628.             err = PyList_Append(list, item);
  629.             Py_DECREF(item);
  630.             if (err < 0)
  631.                 goto fail;
  632.             i = j = i + n;
  633.         }
  634.         else
  635.             i++;
  636.     }
  637.     item = PyString_FromStringAndSize(s+j, (int)(len-j));
  638.     if (item == NULL)
  639.         goto fail;
  640.     err = PyList_Append(list, item);
  641.     Py_DECREF(item);
  642.     if (err < 0)
  643.         goto fail;
  644.  
  645.     return list;
  646.  
  647.  fail:
  648.     Py_DECREF(list);
  649.     return NULL;
  650. }
  651.  
  652.  
  653. static char join__doc__[] =
  654. "S.join(sequence) -> string\n\
  655. \n\
  656. Return a string which is the concatenation of the strings in the\n\
  657. sequence.  The separator between elements is S.";
  658.  
  659. static PyObject *
  660. string_join(self, args)
  661.     PyStringObject *self;
  662.     PyObject *args;
  663. {
  664.     char *sep = PyString_AS_STRING(self);
  665.     int seplen = PyString_GET_SIZE(self);
  666.     PyObject *res = NULL;
  667.     int reslen = 0;
  668.     char *p;
  669.     int seqlen = 0;
  670.     int sz = 100;
  671.     int i, slen;
  672.     PyObject *seq;
  673.  
  674.     if (!PyArg_ParseTuple(args, "O:join", &seq))
  675.         return NULL;
  676.  
  677.     seqlen = PySequence_Length(seq);
  678.     if (seqlen < 0 && PyErr_Occurred())
  679.         return NULL;
  680.  
  681.     if (seqlen == 1) {
  682.         /* Optimization if there's only one item */
  683.         PyObject *item = PySequence_GetItem(seq, 0);
  684.         if (item == NULL)
  685.             return NULL;
  686.         if (!PyString_Check(item) && 
  687.             !PyUnicode_Check(item)) {
  688.                 PyErr_SetString(PyExc_TypeError,
  689.                   "first argument must be sequence of strings");
  690.             Py_DECREF(item);
  691.             return NULL;
  692.         }
  693.         return item;
  694.     }
  695.     if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
  696.         return NULL;
  697.     p = PyString_AsString(res);
  698.  
  699.     /* optimize for lists.  all others (tuples and arbitrary sequences)
  700.      * just use the abstract interface.
  701.      */
  702.     if (PyList_Check(seq)) {
  703.         for (i = 0; i < seqlen; i++) {
  704.             PyObject *item = PyList_GET_ITEM(seq, i);
  705.             if (!PyString_Check(item)){
  706.                 if (PyUnicode_Check(item)) {
  707.                     Py_DECREF(res);
  708.                     return PyUnicode_Join(
  709.                              (PyObject *)self, 
  710.                              seq);
  711.                 }
  712.                 PyErr_Format(PyExc_TypeError,
  713.                          "sequence item %i not a string",
  714.                          i);
  715.                 goto finally;
  716.             }
  717.             slen = PyString_GET_SIZE(item);
  718.             while (reslen + slen + seplen >= sz) {
  719.                 if (_PyString_Resize(&res, sz*2))
  720.                     goto finally;
  721.                 sz *= 2;
  722.                 p = PyString_AsString(res) + reslen;
  723.             }
  724.             if (i > 0) {
  725.                 memcpy(p, sep, seplen);
  726.                 p += seplen;
  727.                 reslen += seplen;
  728.             }
  729.             memcpy(p, PyString_AS_STRING(item), slen);
  730.             p += slen;
  731.             reslen += slen;
  732.         }
  733.     }
  734.     else {
  735.         for (i = 0; i < seqlen; i++) {
  736.             PyObject *item = PySequence_GetItem(seq, i);
  737.             if (!item)
  738.                 goto finally;
  739.             if (!PyString_Check(item)){
  740.                 if (PyUnicode_Check(item)) {
  741.                     Py_DECREF(res);
  742.                     Py_DECREF(item);
  743.                     return PyUnicode_Join(
  744.                              (PyObject *)self, 
  745.                              seq);
  746.                 }
  747.                 Py_DECREF(item);
  748.                 PyErr_Format(PyExc_TypeError,
  749.                          "sequence item %i not a string",
  750.                          i);
  751.                 goto finally;
  752.             }
  753.             slen = PyString_GET_SIZE(item);
  754.             while (reslen + slen + seplen >= sz) {
  755.                 if (_PyString_Resize(&res, sz*2)) {
  756.                     Py_DECREF(item);
  757.                     goto finally;
  758.                 }
  759.                 sz *= 2;
  760.                 p = PyString_AsString(res) + reslen;
  761.             }
  762.             if (i > 0) {
  763.                 memcpy(p, sep, seplen);
  764.                 p += seplen;
  765.                 reslen += seplen;
  766.             }
  767.             memcpy(p, PyString_AS_STRING(item), slen);
  768.             Py_DECREF(item);
  769.             p += slen;
  770.             reslen += slen;
  771.         }
  772.     }
  773.     if (_PyString_Resize(&res, reslen))
  774.         goto finally;
  775.     return res;
  776.  
  777.   finally:
  778.     Py_DECREF(res);
  779.     return NULL;
  780. }
  781.  
  782.  
  783.  
  784. static long
  785. string_find_internal(self, args, dir)
  786.     PyStringObject *self;
  787.     PyObject *args;
  788.         int dir;
  789. {
  790.     const char *s = PyString_AS_STRING(self), *sub;
  791.     int len = PyString_GET_SIZE(self);
  792.     int n, i = 0, last = INT_MAX;
  793.     PyObject *subobj;
  794.  
  795.     if (!PyArg_ParseTuple(args, "O|O&O&:find/rfind/index/rindex", 
  796.         &subobj, _PyEval_SliceIndex, &i, _PyEval_SliceIndex, &last))
  797.         return -2;
  798.     if (PyString_Check(subobj)) {
  799.         sub = PyString_AS_STRING(subobj);
  800.         n = PyString_GET_SIZE(subobj);
  801.     }
  802.     else if (PyUnicode_Check(subobj))
  803.         return PyUnicode_Find((PyObject *)self, subobj, i, last, 1);
  804.     else if (PyObject_AsCharBuffer(subobj, &sub, &n))
  805.         return -2;
  806.  
  807.     if (last > len)
  808.         last = len;
  809.     if (last < 0)
  810.         last += len;
  811.     if (last < 0)
  812.         last = 0;
  813.     if (i < 0)
  814.         i += len;
  815.     if (i < 0)
  816.         i = 0;
  817.  
  818.     if (dir > 0) {
  819.         if (n == 0 && i <= last)
  820.             return (long)i;
  821.         last -= n;
  822.         for (; i <= last; ++i)
  823.             if (s[i] == sub[0] &&
  824.                 (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
  825.                 return (long)i;
  826.     }
  827.     else {
  828.         int j;
  829.         
  830.             if (n == 0 && i <= last)
  831.             return (long)last;
  832.         for (j = last-n; j >= i; --j)
  833.             if (s[j] == sub[0] &&
  834.                 (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
  835.                 return (long)j;
  836.     }
  837.     
  838.     return -1;
  839. }
  840.  
  841.  
  842. static char find__doc__[] =
  843. "S.find(sub [,start [,end]]) -> int\n\
  844. \n\
  845. Return the lowest index in S where substring sub is found,\n\
  846. such that sub is contained within s[start,end].  Optional\n\
  847. arguments start and end are interpreted as in slice notation.\n\
  848. \n\
  849. Return -1 on failure.";
  850.  
  851. static PyObject *
  852. string_find(self, args)
  853.     PyStringObject *self;
  854.     PyObject *args;
  855. {
  856.     long result = string_find_internal(self, args, +1);
  857.     if (result == -2)
  858.         return NULL;
  859.     return PyInt_FromLong(result);
  860. }
  861.  
  862.  
  863. static char index__doc__[] =
  864. "S.index(sub [,start [,end]]) -> int\n\
  865. \n\
  866. Like S.find() but raise ValueError when the substring is not found.";
  867.  
  868. static PyObject *
  869. string_index(self, args)
  870.     PyStringObject *self;
  871.     PyObject *args;
  872. {
  873.     long result = string_find_internal(self, args, +1);
  874.     if (result == -2)
  875.         return NULL;
  876.     if (result == -1) {
  877.         PyErr_SetString(PyExc_ValueError,
  878.                 "substring not found in string.index");
  879.         return NULL;
  880.     }
  881.     return PyInt_FromLong(result);
  882. }
  883.  
  884.  
  885. static char rfind__doc__[] =
  886. "S.rfind(sub [,start [,end]]) -> int\n\
  887. \n\
  888. Return the highest index in S where substring sub is found,\n\
  889. such that sub is contained within s[start,end].  Optional\n\
  890. arguments start and end are interpreted as in slice notation.\n\
  891. \n\
  892. Return -1 on failure.";
  893.  
  894. static PyObject *
  895. string_rfind(self, args)
  896.     PyStringObject *self;
  897.     PyObject *args;
  898. {
  899.     long result = string_find_internal(self, args, -1);
  900.     if (result == -2)
  901.         return NULL;
  902.     return PyInt_FromLong(result);
  903. }
  904.  
  905.  
  906. static char rindex__doc__[] =
  907. "S.rindex(sub [,start [,end]]) -> int\n\
  908. \n\
  909. Like S.rfind() but raise ValueError when the substring is not found.";
  910.  
  911. static PyObject *
  912. string_rindex(self, args)
  913.     PyStringObject *self;
  914.     PyObject *args;
  915. {
  916.     long result = string_find_internal(self, args, -1);
  917.     if (result == -2)
  918.         return NULL;
  919.     if (result == -1) {
  920.         PyErr_SetString(PyExc_ValueError,
  921.                 "substring not found in string.rindex");
  922.         return NULL;
  923.     }
  924.     return PyInt_FromLong(result);
  925. }
  926.  
  927.  
  928. static PyObject *
  929. do_strip(self, args, striptype)
  930.     PyStringObject *self;
  931.     PyObject *args;
  932.     int striptype;
  933. {
  934.     char *s = PyString_AS_STRING(self);
  935.     int len = PyString_GET_SIZE(self), i, j;
  936.  
  937.     if (!PyArg_ParseTuple(args, ":strip"))
  938.         return NULL;
  939.  
  940.     i = 0;
  941.     if (striptype != RIGHTSTRIP) {
  942.         while (i < len && isspace(Py_CHARMASK(s[i]))) {
  943.             i++;
  944.         }
  945.     }
  946.  
  947.     j = len;
  948.     if (striptype != LEFTSTRIP) {
  949.         do {
  950.             j--;
  951.         } while (j >= i && isspace(Py_CHARMASK(s[j])));
  952.         j++;
  953.     }
  954.  
  955.     if (i == 0 && j == len) {
  956.         Py_INCREF(self);
  957.         return (PyObject*)self;
  958.     }
  959.     else
  960.         return PyString_FromStringAndSize(s+i, j-i);
  961. }
  962.  
  963.  
  964. static char strip__doc__[] =
  965. "S.strip() -> string\n\
  966. \n\
  967. Return a copy of the string S with leading and trailing\n\
  968. whitespace removed.";
  969.  
  970. static PyObject *
  971. string_strip(self, args)
  972.     PyStringObject *self;
  973.     PyObject *args;
  974. {
  975.     return do_strip(self, args, BOTHSTRIP);
  976. }
  977.  
  978.  
  979. static char lstrip__doc__[] =
  980. "S.lstrip() -> string\n\
  981. \n\
  982. Return a copy of the string S with leading whitespace removed.";
  983.  
  984. static PyObject *
  985. string_lstrip(self, args)
  986.     PyStringObject *self;
  987.     PyObject *args;
  988. {
  989.     return do_strip(self, args, LEFTSTRIP);
  990. }
  991.  
  992.  
  993. static char rstrip__doc__[] =
  994. "S.rstrip() -> string\n\
  995. \n\
  996. Return a copy of the string S with trailing whitespace removed.";
  997.  
  998. static PyObject *
  999. string_rstrip(self, args)
  1000.     PyStringObject *self;
  1001.     PyObject *args;
  1002. {
  1003.     return do_strip(self, args, RIGHTSTRIP);
  1004. }
  1005.  
  1006.  
  1007. static char lower__doc__[] =
  1008. "S.lower() -> string\n\
  1009. \n\
  1010. Return a copy of the string S converted to lowercase.";
  1011.  
  1012. static PyObject *
  1013. string_lower(self, args)
  1014.     PyStringObject *self;
  1015.     PyObject *args;
  1016. {
  1017.     char *s = PyString_AS_STRING(self), *s_new;
  1018.     int i, n = PyString_GET_SIZE(self);
  1019.     PyObject *new;
  1020.  
  1021.     if (!PyArg_ParseTuple(args, ":lower"))
  1022.         return NULL;
  1023.     new = PyString_FromStringAndSize(NULL, n);
  1024.     if (new == NULL)
  1025.         return NULL;
  1026.     s_new = PyString_AsString(new);
  1027.     for (i = 0; i < n; i++) {
  1028.         int c = Py_CHARMASK(*s++);
  1029.         if (isupper(c)) {
  1030.             *s_new = tolower(c);
  1031.         } else
  1032.             *s_new = c;
  1033.         s_new++;
  1034.     }
  1035.     return new;
  1036. }
  1037.  
  1038.  
  1039. static char upper__doc__[] =
  1040. "S.upper() -> string\n\
  1041. \n\
  1042. Return a copy of the string S converted to uppercase.";
  1043.  
  1044. static PyObject *
  1045. string_upper(self, args)
  1046.     PyStringObject *self;
  1047.     PyObject *args;
  1048. {
  1049.     char *s = PyString_AS_STRING(self), *s_new;
  1050.     int i, n = PyString_GET_SIZE(self);
  1051.     PyObject *new;
  1052.  
  1053.     if (!PyArg_ParseTuple(args, ":upper"))
  1054.         return NULL;
  1055.     new = PyString_FromStringAndSize(NULL, n);
  1056.     if (new == NULL)
  1057.         return NULL;
  1058.     s_new = PyString_AsString(new);
  1059.     for (i = 0; i < n; i++) {
  1060.         int c = Py_CHARMASK(*s++);
  1061.         if (islower(c)) {
  1062.             *s_new = toupper(c);
  1063.         } else
  1064.             *s_new = c;
  1065.         s_new++;
  1066.     }
  1067.     return new;
  1068. }
  1069.  
  1070.  
  1071. static char title__doc__[] =
  1072. "S.title() -> string\n\
  1073. \n\
  1074. Return a titlecased version of S, i.e. words start with uppercase\n\
  1075. characters, all remaining cased characters have lowercase.";
  1076.  
  1077. static PyObject*
  1078. string_title(PyUnicodeObject *self, PyObject *args)
  1079. {
  1080.     char *s = PyString_AS_STRING(self), *s_new;
  1081.     int i, n = PyString_GET_SIZE(self);
  1082.     int previous_is_cased = 0;
  1083.     PyObject *new;
  1084.  
  1085.     if (!PyArg_ParseTuple(args, ":title"))
  1086.         return NULL;
  1087.     new = PyString_FromStringAndSize(NULL, n);
  1088.     if (new == NULL)
  1089.         return NULL;
  1090.     s_new = PyString_AsString(new);
  1091.     for (i = 0; i < n; i++) {
  1092.         int c = Py_CHARMASK(*s++);
  1093.         if (islower(c)) {
  1094.             if (!previous_is_cased)
  1095.                 c = toupper(c);
  1096.             previous_is_cased = 1;
  1097.         } else if (isupper(c)) {
  1098.             if (previous_is_cased)
  1099.                 c = tolower(c);
  1100.             previous_is_cased = 1;
  1101.         } else
  1102.             previous_is_cased = 0;
  1103.         *s_new++ = c;
  1104.     }
  1105.     return new;
  1106. }
  1107.  
  1108. static char capitalize__doc__[] =
  1109. "S.capitalize() -> string\n\
  1110. \n\
  1111. Return a copy of the string S with only its first character\n\
  1112. capitalized.";
  1113.  
  1114. static PyObject *
  1115. string_capitalize(self, args)
  1116.     PyStringObject *self;
  1117.     PyObject *args;
  1118. {
  1119.     char *s = PyString_AS_STRING(self), *s_new;
  1120.     int i, n = PyString_GET_SIZE(self);
  1121.     PyObject *new;
  1122.  
  1123.     if (!PyArg_ParseTuple(args, ":capitalize"))
  1124.         return NULL;
  1125.     new = PyString_FromStringAndSize(NULL, n);
  1126.     if (new == NULL)
  1127.         return NULL;
  1128.     s_new = PyString_AsString(new);
  1129.     if (0 < n) {
  1130.         int c = Py_CHARMASK(*s++);
  1131.         if (islower(c))
  1132.             *s_new = toupper(c);
  1133.         else
  1134.             *s_new = c;
  1135.         s_new++;
  1136.     }
  1137.     for (i = 1; i < n; i++) {
  1138.         int c = Py_CHARMASK(*s++);
  1139.         if (isupper(c))
  1140.             *s_new = tolower(c);
  1141.         else
  1142.             *s_new = c;
  1143.         s_new++;
  1144.     }
  1145.     return new;
  1146. }
  1147.  
  1148.  
  1149. static char count__doc__[] =
  1150. "S.count(sub[, start[, end]]) -> int\n\
  1151. \n\
  1152. Return the number of occurrences of substring sub in string\n\
  1153. S[start:end].  Optional arguments start and end are\n\
  1154. interpreted as in slice notation.";
  1155.  
  1156. static PyObject *
  1157. string_count(self, args)
  1158.     PyStringObject *self;
  1159.     PyObject *args;
  1160. {
  1161.     const char *s = PyString_AS_STRING(self), *sub;
  1162.     int len = PyString_GET_SIZE(self), n;
  1163.     int i = 0, last = INT_MAX;
  1164.     int m, r;
  1165.     PyObject *subobj;
  1166.  
  1167.     if (!PyArg_ParseTuple(args, "O|O&O&:count", &subobj,
  1168.         _PyEval_SliceIndex, &i, _PyEval_SliceIndex, &last))
  1169.         return NULL;
  1170.  
  1171.     if (PyString_Check(subobj)) {
  1172.         sub = PyString_AS_STRING(subobj);
  1173.         n = PyString_GET_SIZE(subobj);
  1174.     }
  1175.     else if (PyUnicode_Check(subobj))
  1176.         return PyInt_FromLong(
  1177.                 PyUnicode_Count((PyObject *)self, subobj, i, last));
  1178.     else if (PyObject_AsCharBuffer(subobj, &sub, &n))
  1179.         return NULL;
  1180.  
  1181.     if (last > len)
  1182.         last = len;
  1183.     if (last < 0)
  1184.         last += len;
  1185.     if (last < 0)
  1186.         last = 0;
  1187.     if (i < 0)
  1188.         i += len;
  1189.     if (i < 0)
  1190.         i = 0;
  1191.     m = last + 1 - n;
  1192.     if (n == 0)
  1193.         return PyInt_FromLong((long) (m-i));
  1194.  
  1195.     r = 0;
  1196.     while (i < m) {
  1197.         if (!memcmp(s+i, sub, n)) {
  1198.             r++;
  1199.             i += n;
  1200.         } else {
  1201.             i++;
  1202.         }
  1203.     }
  1204.     return PyInt_FromLong((long) r);
  1205. }
  1206.  
  1207.  
  1208. static char swapcase__doc__[] =
  1209. "S.swapcase() -> string\n\
  1210. \n\
  1211. Return a copy of the string S with uppercase characters\n\
  1212. converted to lowercase and vice versa.";
  1213.  
  1214. static PyObject *
  1215. string_swapcase(self, args)
  1216.     PyStringObject *self;
  1217.     PyObject *args;
  1218. {
  1219.     char *s = PyString_AS_STRING(self), *s_new;
  1220.     int i, n = PyString_GET_SIZE(self);
  1221.     PyObject *new;
  1222.  
  1223.     if (!PyArg_ParseTuple(args, ":swapcase"))
  1224.         return NULL;
  1225.     new = PyString_FromStringAndSize(NULL, n);
  1226.     if (new == NULL)
  1227.         return NULL;
  1228.     s_new = PyString_AsString(new);
  1229.     for (i = 0; i < n; i++) {
  1230.         int c = Py_CHARMASK(*s++);
  1231.         if (islower(c)) {
  1232.             *s_new = toupper(c);
  1233.         }
  1234.         else if (isupper(c)) {
  1235.             *s_new = tolower(c);
  1236.         }
  1237.         else
  1238.             *s_new = c;
  1239.         s_new++;
  1240.     }
  1241.     return new;
  1242. }
  1243.  
  1244.  
  1245. static char translate__doc__[] =
  1246. "S.translate(table [,deletechars]) -> string\n\
  1247. \n\
  1248. Return a copy of the string S, where all characters occurring\n\
  1249. in the optional argument deletechars are removed, and the\n\
  1250. remaining characters have been mapped through the given\n\
  1251. translation table, which must be a string of length 256.";
  1252.  
  1253. static PyObject *
  1254. string_translate(self, args)
  1255.     PyStringObject *self;
  1256.     PyObject *args;
  1257. {
  1258.     register char *input, *output;
  1259.     register const char *table;
  1260.     register int i, c, changed = 0;
  1261.     PyObject *input_obj = (PyObject*)self;
  1262.     const char *table1, *output_start, *del_table=NULL;
  1263.     int inlen, tablen, dellen = 0;
  1264.     PyObject *result;
  1265.     int trans_table[256];
  1266.     PyObject *tableobj, *delobj = NULL;
  1267.  
  1268.     if (!PyArg_ParseTuple(args, "O|O:translate",
  1269.                   &tableobj, &delobj))
  1270.         return NULL;
  1271.  
  1272.     if (PyString_Check(tableobj)) {
  1273.         table1 = PyString_AS_STRING(tableobj);
  1274.         tablen = PyString_GET_SIZE(tableobj);
  1275.     }
  1276.     else if (PyUnicode_Check(tableobj)) {
  1277.         /* Unicode .translate() does not support the deletechars 
  1278.            parameter; instead a mapping to None will cause characters
  1279.            to be deleted. */
  1280.         if (delobj != NULL) {
  1281.             PyErr_SetString(PyExc_TypeError,
  1282.             "deletions are implemented differently for unicode");
  1283.             return NULL;
  1284.         }
  1285.         return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
  1286.     }
  1287.     else if (PyObject_AsCharBuffer(tableobj, &table1, &tablen))
  1288.         return NULL;
  1289.  
  1290.     if (delobj != NULL) {
  1291.         if (PyString_Check(delobj)) {
  1292.             del_table = PyString_AS_STRING(delobj);
  1293.             dellen = PyString_GET_SIZE(delobj);
  1294.         }
  1295.         else if (PyUnicode_Check(delobj)) {
  1296.             PyErr_SetString(PyExc_TypeError,
  1297.             "deletions are implemented differently for unicode");
  1298.             return NULL;
  1299.         }
  1300.         else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
  1301.             return NULL;
  1302.  
  1303.         if (tablen != 256) {
  1304.             PyErr_SetString(PyExc_ValueError,
  1305.               "translation table must be 256 characters long");
  1306.             return NULL;
  1307.         }
  1308.     }
  1309.     else {
  1310.         del_table = NULL;
  1311.         dellen = 0;
  1312.     }
  1313.  
  1314.     table = table1;
  1315.     inlen = PyString_Size(input_obj);
  1316.     result = PyString_FromStringAndSize((char *)NULL, inlen);
  1317.     if (result == NULL)
  1318.         return NULL;
  1319.     output_start = output = PyString_AsString(result);
  1320.     input = PyString_AsString(input_obj);
  1321.  
  1322.     if (dellen == 0) {
  1323.         /* If no deletions are required, use faster code */
  1324.         for (i = inlen; --i >= 0; ) {
  1325.             c = Py_CHARMASK(*input++);
  1326.             if (Py_CHARMASK((*output++ = table[c])) != c)
  1327.                 changed = 1;
  1328.         }
  1329.         if (changed)
  1330.             return result;
  1331.         Py_DECREF(result);
  1332.         Py_INCREF(input_obj);
  1333.         return input_obj;
  1334.     }
  1335.  
  1336.     for (i = 0; i < 256; i++)
  1337.         trans_table[i] = Py_CHARMASK(table[i]);
  1338.  
  1339.     for (i = 0; i < dellen; i++)
  1340.         trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
  1341.  
  1342.     for (i = inlen; --i >= 0; ) {
  1343.         c = Py_CHARMASK(*input++);
  1344.         if (trans_table[c] != -1)
  1345.             if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
  1346.                 continue;
  1347.         changed = 1;
  1348.     }
  1349.     if (!changed) {
  1350.         Py_DECREF(result);
  1351.         Py_INCREF(input_obj);
  1352.         return input_obj;
  1353.     }
  1354.     /* Fix the size of the resulting string */
  1355.     if (inlen > 0 &&_PyString_Resize(&result, output-output_start))
  1356.         return NULL;
  1357.     return result;
  1358. }
  1359.  
  1360.  
  1361. /* What follows is used for implementing replace().  Perry Stoll. */
  1362.  
  1363. /*
  1364.   mymemfind
  1365.  
  1366.   strstr replacement for arbitrary blocks of memory.
  1367.  
  1368.   Locates the first occurrence in the memory pointed to by MEM of the
  1369.   contents of memory pointed to by PAT.  Returns the index into MEM if
  1370.   found, or -1 if not found.  If len of PAT is greater than length of
  1371.   MEM, the function returns -1.
  1372. */
  1373. static int 
  1374. mymemfind(mem, len, pat, pat_len)
  1375.     char *mem;
  1376.     int len;
  1377.     char *pat;
  1378.     int pat_len;
  1379. {
  1380.     register int ii;
  1381.  
  1382.     /* pattern can not occur in the last pat_len-1 chars */
  1383.     len -= pat_len;
  1384.  
  1385.     for (ii = 0; ii <= len; ii++) {
  1386.         if (mem[ii] == pat[0] &&
  1387.             (pat_len == 1 ||
  1388.              memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
  1389.             return ii;
  1390.         }
  1391.     }
  1392.     return -1;
  1393. }
  1394.  
  1395. /*
  1396.   mymemcnt
  1397.  
  1398.    Return the number of distinct times PAT is found in MEM.
  1399.    meaning mem=1111 and pat==11 returns 2.
  1400.            mem=11111 and pat==11 also return 2.
  1401.  */
  1402. static int 
  1403. mymemcnt(mem, len, pat, pat_len)
  1404.     char *mem;
  1405.     int len;
  1406.     char *pat;
  1407.     int pat_len;
  1408. {
  1409.     register int offset = 0;
  1410.     int nfound = 0;
  1411.  
  1412.     while (len >= 0) {
  1413.         offset = mymemfind(mem, len, pat, pat_len);
  1414.         if (offset == -1)
  1415.             break;
  1416.         mem += offset + pat_len;
  1417.         len -= offset + pat_len;
  1418.         nfound++;
  1419.     }
  1420.     return nfound;
  1421. }
  1422.  
  1423. /*
  1424.    mymemreplace
  1425.  
  1426.    Return a string in which all occurences of PAT in memory STR are
  1427.    replaced with SUB.
  1428.  
  1429.    If length of PAT is less than length of STR or there are no occurences
  1430.    of PAT in STR, then the original string is returned. Otherwise, a new
  1431.    string is allocated here and returned.
  1432.  
  1433.    on return, out_len is:
  1434.        the length of output string, or
  1435.        -1 if the input string is returned, or
  1436.        unchanged if an error occurs (no memory).
  1437.  
  1438.    return value is:
  1439.        the new string allocated locally, or
  1440.        NULL if an error occurred.
  1441. */
  1442. static char *
  1443. mymemreplace(str, len, pat, pat_len, sub, sub_len, count, out_len)
  1444.     char *str;
  1445.     int len;     /* input string  */
  1446.     char *pat;
  1447.     int pat_len; /* pattern string to find */
  1448.     char *sub;
  1449.     int sub_len; /* substitution string */
  1450.     int count;   /* number of replacements */
  1451.     int *out_len;
  1452.  
  1453. {
  1454.     char *out_s;
  1455.     char *new_s;
  1456.     int nfound, offset, new_len;
  1457.  
  1458.     if (len == 0 || pat_len > len)
  1459.         goto return_same;
  1460.  
  1461.     /* find length of output string */
  1462.     nfound = mymemcnt(str, len, pat, pat_len);
  1463.     if (count < 0)
  1464.         count = INT_MAX;
  1465.     else if (nfound > count)
  1466.         nfound = count;
  1467.     if (nfound == 0)
  1468.         goto return_same;
  1469.     new_len = len + nfound*(sub_len - pat_len);
  1470.  
  1471.     new_s = (char *)PyMem_MALLOC(new_len);
  1472.     if (new_s == NULL) return NULL;
  1473.  
  1474.     *out_len = new_len;
  1475.     out_s = new_s;
  1476.  
  1477.     while (len > 0) {
  1478.         /* find index of next instance of pattern */
  1479.         offset = mymemfind(str, len, pat, pat_len);
  1480.         /* if not found,  break out of loop */
  1481.         if (offset == -1) break;
  1482.  
  1483.         /* copy non matching part of input string */
  1484.         memcpy(new_s, str, offset); /* copy part of str before pat */
  1485.         str += offset + pat_len; /* move str past pattern */
  1486.         len -= offset + pat_len; /* reduce length of str remaining */
  1487.  
  1488.         /* copy substitute into the output string */
  1489.         new_s += offset; /* move new_s to dest for sub string */
  1490.         memcpy(new_s, sub, sub_len); /* copy substring into new_s */
  1491.         new_s += sub_len; /* offset new_s past sub string */
  1492.  
  1493.         /* break when we've done count replacements */
  1494.         if (--count == 0) break;
  1495.     }
  1496.     /* copy any remaining values into output string */
  1497.     if (len > 0)
  1498.         memcpy(new_s, str, len);
  1499.     return out_s;
  1500.  
  1501.   return_same:
  1502.     *out_len = -1;
  1503.     return str;
  1504. }
  1505.  
  1506.  
  1507. static char replace__doc__[] =
  1508. "S.replace (old, new[, maxsplit]) -> string\n\
  1509. \n\
  1510. Return a copy of string S with all occurrences of substring\n\
  1511. old replaced by new.  If the optional argument maxsplit is\n\
  1512. given, only the first maxsplit occurrences are replaced.";
  1513.  
  1514. static PyObject *
  1515. string_replace(self, args)
  1516.     PyStringObject *self;
  1517.     PyObject *args;
  1518. {
  1519.     const char *str = PyString_AS_STRING(self), *sub, *repl;
  1520.     char *new_s;
  1521.     int len = PyString_GET_SIZE(self), sub_len, repl_len, out_len;
  1522.     int count = -1;
  1523.     PyObject *new;
  1524.     PyObject *subobj, *replobj;
  1525.  
  1526.     if (!PyArg_ParseTuple(args, "OO|i:replace",
  1527.                   &subobj, &replobj, &count))
  1528.         return NULL;
  1529.  
  1530.     if (PyString_Check(subobj)) {
  1531.         sub = PyString_AS_STRING(subobj);
  1532.         sub_len = PyString_GET_SIZE(subobj);
  1533.     }
  1534.     else if (PyUnicode_Check(subobj))
  1535.         return PyUnicode_Replace((PyObject *)self, 
  1536.                      subobj, replobj, count);
  1537.     else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
  1538.         return NULL;
  1539.  
  1540.     if (PyString_Check(replobj)) {
  1541.         repl = PyString_AS_STRING(replobj);
  1542.         repl_len = PyString_GET_SIZE(replobj);
  1543.     }
  1544.     else if (PyUnicode_Check(replobj))
  1545.         return PyUnicode_Replace((PyObject *)self, 
  1546.                      subobj, replobj, count);
  1547.     else if (PyObject_AsCharBuffer(replobj, &repl, &repl_len))
  1548.         return NULL;
  1549.  
  1550.     if (sub_len <= 0) {
  1551.         PyErr_SetString(PyExc_ValueError, "empty pattern string");
  1552.         return NULL;
  1553.     }
  1554.     new_s = mymemreplace(str,len,sub,sub_len,repl,repl_len,count,&out_len);
  1555.     if (new_s == NULL) {
  1556.         PyErr_NoMemory();
  1557.         return NULL;
  1558.     }
  1559.     if (out_len == -1) {
  1560.         /* we're returning another reference to self */
  1561.         new = (PyObject*)self;
  1562.         Py_INCREF(new);
  1563.     }
  1564.     else {
  1565.         new = PyString_FromStringAndSize(new_s, out_len);
  1566.         PyMem_FREE(new_s);
  1567.     }
  1568.     return new;
  1569. }
  1570.  
  1571.  
  1572. static char startswith__doc__[] =
  1573. "S.startswith(prefix[, start[, end]]) -> int\n\
  1574. \n\
  1575. Return 1 if S starts with the specified prefix, otherwise return 0.  With\n\
  1576. optional start, test S beginning at that position.  With optional end, stop\n\
  1577. comparing S at that position.";
  1578.  
  1579. static PyObject *
  1580. string_startswith(self, args)
  1581.     PyStringObject *self;
  1582.     PyObject *args;
  1583. {
  1584.     const char* str = PyString_AS_STRING(self);
  1585.     int len = PyString_GET_SIZE(self);
  1586.     const char* prefix;
  1587.     int plen;
  1588.     int start = 0;
  1589.     int end = -1;
  1590.     PyObject *subobj;
  1591.  
  1592.     if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
  1593.         _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  1594.         return NULL;
  1595.     if (PyString_Check(subobj)) {
  1596.         prefix = PyString_AS_STRING(subobj);
  1597.         plen = PyString_GET_SIZE(subobj);
  1598.     }
  1599.     else if (PyUnicode_Check(subobj))
  1600.         return PyInt_FromLong(
  1601.                 PyUnicode_Tailmatch((PyObject *)self, 
  1602.                         subobj, start, end, -1));
  1603.     else if (PyObject_AsCharBuffer(subobj, &prefix, &plen))
  1604.         return NULL;
  1605.  
  1606.     /* adopt Java semantics for index out of range.  it is legal for
  1607.      * offset to be == plen, but this only returns true if prefix is
  1608.      * the empty string.
  1609.      */
  1610.     if (start < 0 || start+plen > len)
  1611.         return PyInt_FromLong(0);
  1612.  
  1613.     if (!memcmp(str+start, prefix, plen)) {
  1614.         /* did the match end after the specified end? */
  1615.         if (end < 0)
  1616.             return PyInt_FromLong(1);
  1617.         else if (end - start < plen)
  1618.             return PyInt_FromLong(0);
  1619.         else
  1620.             return PyInt_FromLong(1);
  1621.     }
  1622.     else return PyInt_FromLong(0);
  1623. }
  1624.  
  1625.  
  1626. static char endswith__doc__[] =
  1627. "S.endswith(suffix[, start[, end]]) -> int\n\
  1628. \n\
  1629. Return 1 if S ends with the specified suffix, otherwise return 0.  With\n\
  1630. optional start, test S beginning at that position.  With optional end, stop\n\
  1631. comparing S at that position.";
  1632.  
  1633. static PyObject *
  1634. string_endswith(self, args)
  1635.     PyStringObject *self;
  1636.     PyObject *args;
  1637. {
  1638.     const char* str = PyString_AS_STRING(self);
  1639.     int len = PyString_GET_SIZE(self);
  1640.     const char* suffix;
  1641.     int slen;
  1642.     int start = 0;
  1643.     int end = -1;
  1644.     int lower, upper;
  1645.     PyObject *subobj;
  1646.  
  1647.     if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
  1648.         _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
  1649.         return NULL;
  1650.     if (PyString_Check(subobj)) {
  1651.         suffix = PyString_AS_STRING(subobj);
  1652.         slen = PyString_GET_SIZE(subobj);
  1653.     }
  1654.     else if (PyUnicode_Check(subobj))
  1655.         return PyInt_FromLong(
  1656.                 PyUnicode_Tailmatch((PyObject *)self, 
  1657.                         subobj, start, end, +1));
  1658.     else if (PyObject_AsCharBuffer(subobj, &suffix, &slen))
  1659.         return NULL;
  1660.  
  1661.     if (start < 0 || start > len || slen > len)
  1662.         return PyInt_FromLong(0);
  1663.  
  1664.     upper = (end >= 0 && end <= len) ? end : len;
  1665.     lower = (upper - slen) > start ? (upper - slen) : start;
  1666.  
  1667.     if (upper-lower >= slen && !memcmp(str+lower, suffix, slen))
  1668.         return PyInt_FromLong(1);
  1669.     else return PyInt_FromLong(0);
  1670. }
  1671.  
  1672.  
  1673. static char expandtabs__doc__[] =
  1674. "S.expandtabs([tabsize]) -> string\n\
  1675. \n\
  1676. Return a copy of S where all tab characters are expanded using spaces.\n\
  1677. If tabsize is not given, a tab size of 8 characters is assumed.";
  1678.  
  1679. static PyObject*
  1680. string_expandtabs(PyStringObject *self, PyObject *args)
  1681. {
  1682.     const char *e, *p;
  1683.     char *q;
  1684.     int i, j;
  1685.     PyObject *u;
  1686.     int tabsize = 8;
  1687.  
  1688.     if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
  1689.     return NULL;
  1690.  
  1691.     /* First pass: determine size of ouput string */
  1692.     i = j = 0;
  1693.     e = PyString_AS_STRING(self) + PyString_GET_SIZE(self);
  1694.     for (p = PyString_AS_STRING(self); p < e; p++)
  1695.         if (*p == '\t') {
  1696.         if (tabsize > 0)
  1697.         j += tabsize - (j % tabsize);
  1698.     }
  1699.         else {
  1700.             j++;
  1701.             if (*p == '\n' || *p == '\r') {
  1702.                 i += j;
  1703.                 j = 0;
  1704.             }
  1705.         }
  1706.  
  1707.     /* Second pass: create output string and fill it */
  1708.     u = PyString_FromStringAndSize(NULL, i + j);
  1709.     if (!u)
  1710.         return NULL;
  1711.  
  1712.     j = 0;
  1713.     q = PyString_AS_STRING(u);
  1714.  
  1715.     for (p = PyString_AS_STRING(self); p < e; p++)
  1716.         if (*p == '\t') {
  1717.         if (tabsize > 0) {
  1718.         i = tabsize - (j % tabsize);
  1719.         j += i;
  1720.         while (i--)
  1721.             *q++ = ' ';
  1722.         }
  1723.     }
  1724.     else {
  1725.             j++;
  1726.         *q++ = *p;
  1727.             if (*p == '\n' || *p == '\r')
  1728.                 j = 0;
  1729.         }
  1730.  
  1731.     return u;
  1732. }
  1733.  
  1734. static 
  1735. PyObject *pad(PyStringObject *self, 
  1736.           int left, 
  1737.           int right,
  1738.           char fill)
  1739. {
  1740.     PyObject *u;
  1741.  
  1742.     if (left < 0)
  1743.         left = 0;
  1744.     if (right < 0)
  1745.         right = 0;
  1746.  
  1747.     if (left == 0 && right == 0) {
  1748.         Py_INCREF(self);
  1749.         return (PyObject *)self;
  1750.     }
  1751.  
  1752.     u = PyString_FromStringAndSize(NULL, 
  1753.                    left + PyString_GET_SIZE(self) + right);
  1754.     if (u) {
  1755.         if (left)
  1756.             memset(PyString_AS_STRING(u), fill, left);
  1757.         memcpy(PyString_AS_STRING(u) + left, 
  1758.            PyString_AS_STRING(self), 
  1759.            PyString_GET_SIZE(self));
  1760.         if (right)
  1761.             memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
  1762.            fill, right);
  1763.     }
  1764.  
  1765.     return u;
  1766. }
  1767.  
  1768. static char ljust__doc__[] =
  1769. "S.ljust(width) -> string\n\
  1770. \n\
  1771. Return S left justified in a string of length width. Padding is\n\
  1772. done using spaces.";
  1773.  
  1774. static PyObject *
  1775. string_ljust(PyStringObject *self, PyObject *args)
  1776. {
  1777.     int width;
  1778.     if (!PyArg_ParseTuple(args, "i:ljust", &width))
  1779.         return NULL;
  1780.  
  1781.     if (PyString_GET_SIZE(self) >= width) {
  1782.         Py_INCREF(self);
  1783.         return (PyObject*) self;
  1784.     }
  1785.  
  1786.     return pad(self, 0, width - PyString_GET_SIZE(self), ' ');
  1787. }
  1788.  
  1789.  
  1790. static char rjust__doc__[] =
  1791. "S.rjust(width) -> string\n\
  1792. \n\
  1793. Return S right justified in a string of length width. Padding is\n\
  1794. done using spaces.";
  1795.  
  1796. static PyObject *
  1797. string_rjust(PyStringObject *self, PyObject *args)
  1798. {
  1799.     int width;
  1800.     if (!PyArg_ParseTuple(args, "i:rjust", &width))
  1801.         return NULL;
  1802.  
  1803.     if (PyString_GET_SIZE(self) >= width) {
  1804.         Py_INCREF(self);
  1805.         return (PyObject*) self;
  1806.     }
  1807.  
  1808.     return pad(self, width - PyString_GET_SIZE(self), 0, ' ');
  1809. }
  1810.  
  1811.  
  1812. static char center__doc__[] =
  1813. "S.center(width) -> string\n\
  1814. \n\
  1815. Return S centered in a string of length width. Padding is done\n\
  1816. using spaces.";
  1817.  
  1818. static PyObject *
  1819. string_center(PyStringObject *self, PyObject *args)
  1820. {
  1821.     int marg, left;
  1822.     int width;
  1823.  
  1824.     if (!PyArg_ParseTuple(args, "i:center", &width))
  1825.         return NULL;
  1826.  
  1827.     if (PyString_GET_SIZE(self) >= width) {
  1828.         Py_INCREF(self);
  1829.         return (PyObject*) self;
  1830.     }
  1831.  
  1832.     marg = width - PyString_GET_SIZE(self);
  1833.     left = marg / 2 + (marg & width & 1);
  1834.  
  1835.     return pad(self, left, marg - left, ' ');
  1836. }
  1837.  
  1838. #if 0
  1839. static char zfill__doc__[] =
  1840. "S.zfill(width) -> string\n\
  1841. \n\
  1842. Pad a numeric string x with zeros on the left, to fill a field\n\
  1843. of the specified width. The string x is never truncated.";
  1844.  
  1845. static PyObject *
  1846. string_zfill(PyStringObject *self, PyObject *args)
  1847. {
  1848.     int fill;
  1849.     PyObject *u;
  1850.     char *str;
  1851.  
  1852.     int width;
  1853.     if (!PyArg_ParseTuple(args, "i:zfill", &width))
  1854.         return NULL;
  1855.  
  1856.     if (PyString_GET_SIZE(self) >= width) {
  1857.         Py_INCREF(self);
  1858.         return (PyObject*) self;
  1859.     }
  1860.  
  1861.     fill = width - PyString_GET_SIZE(self);
  1862.  
  1863.     u = pad(self, fill, 0, '0');
  1864.     if (u == NULL)
  1865.     return NULL;
  1866.  
  1867.     str = PyString_AS_STRING(u);
  1868.     if (str[fill] == '+' || str[fill] == '-') {
  1869.         /* move sign to beginning of string */
  1870.         str[0] = str[fill];
  1871.         str[fill] = '0';
  1872.     }
  1873.  
  1874.     return u;
  1875. }
  1876. #endif
  1877.  
  1878. static char isspace__doc__[] =
  1879. "S.isspace() -> int\n\
  1880. \n\
  1881. Return 1 if there are only whitespace characters in S,\n\
  1882. 0 otherwise.";
  1883.  
  1884. static PyObject*
  1885. string_isspace(PyStringObject *self, PyObject *args)
  1886. {
  1887.     register const unsigned char *p = (unsigned char *) PyString_AS_STRING(self);
  1888.     register const unsigned char *e;
  1889.  
  1890.     if (!PyArg_NoArgs(args))
  1891.         return NULL;
  1892.  
  1893.     /* Shortcut for single character strings */
  1894.     if (PyString_GET_SIZE(self) == 1 &&
  1895.     isspace(*p))
  1896.     return PyInt_FromLong(1);
  1897.  
  1898.     e = p + PyString_GET_SIZE(self);
  1899.     for (; p < e; p++) {
  1900.     if (!isspace(*p))
  1901.         return PyInt_FromLong(0);
  1902.     }
  1903.     return PyInt_FromLong(1);
  1904. }
  1905.  
  1906.  
  1907. static char isdigit__doc__[] =
  1908. "S.isdigit() -> int\n\
  1909. \n\
  1910. Return 1 if there are only digit characters in S,\n\
  1911. 0 otherwise.";
  1912.  
  1913. static PyObject*
  1914. string_isdigit(PyStringObject *self, PyObject *args)
  1915. {
  1916.     register const unsigned char *p = (unsigned char *) PyString_AS_STRING(self);
  1917.     register const unsigned char *e;
  1918.  
  1919.     if (!PyArg_NoArgs(args))
  1920.         return NULL;
  1921.  
  1922.     /* Shortcut for single character strings */
  1923.     if (PyString_GET_SIZE(self) == 1 &&
  1924.     isdigit(*p))
  1925.     return PyInt_FromLong(1);
  1926.  
  1927.     e = p + PyString_GET_SIZE(self);
  1928.     for (; p < e; p++) {
  1929.     if (!isdigit(*p))
  1930.         return PyInt_FromLong(0);
  1931.     }
  1932.     return PyInt_FromLong(1);
  1933. }
  1934.  
  1935.  
  1936. static char islower__doc__[] =
  1937. "S.islower() -> int\n\
  1938. \n\
  1939. Return 1 if  all cased characters in S are lowercase and there is\n\
  1940. at least one cased character in S, 0 otherwise.";
  1941.  
  1942. static PyObject*
  1943. string_islower(PyStringObject *self, PyObject *args)
  1944. {
  1945.     register const unsigned char *p = (unsigned char *) PyString_AS_STRING(self);
  1946.     register const unsigned char *e;
  1947.     int cased;
  1948.  
  1949.     if (!PyArg_NoArgs(args))
  1950.         return NULL;
  1951.  
  1952.     /* Shortcut for single character strings */
  1953.     if (PyString_GET_SIZE(self) == 1)
  1954.     return PyInt_FromLong(islower(*p) != 0);
  1955.  
  1956.     e = p + PyString_GET_SIZE(self);
  1957.     cased = 0;
  1958.     for (; p < e; p++) {
  1959.     if (isupper(*p))
  1960.         return PyInt_FromLong(0);
  1961.     else if (!cased && islower(*p))
  1962.         cased = 1;
  1963.     }
  1964.     return PyInt_FromLong(cased);
  1965. }
  1966.  
  1967.  
  1968. static char isupper__doc__[] =
  1969. "S.isupper() -> int\n\
  1970. \n\
  1971. Return 1 if  all cased characters in S are uppercase and there is\n\
  1972. at least one cased character in S, 0 otherwise.";
  1973.  
  1974. static PyObject*
  1975. string_isupper(PyStringObject *self, PyObject *args)
  1976. {
  1977.     register const unsigned char *p = (unsigned char *) PyString_AS_STRING(self);
  1978.     register const unsigned char *e;
  1979.     int cased;
  1980.  
  1981.     if (!PyArg_NoArgs(args))
  1982.         return NULL;
  1983.  
  1984.     /* Shortcut for single character strings */
  1985.     if (PyString_GET_SIZE(self) == 1)
  1986.     return PyInt_FromLong(isupper(*p) != 0);
  1987.  
  1988.     e = p + PyString_GET_SIZE(self);
  1989.     cased = 0;
  1990.     for (; p < e; p++) {
  1991.     if (islower(*p))
  1992.         return PyInt_FromLong(0);
  1993.     else if (!cased && isupper(*p))
  1994.         cased = 1;
  1995.     }
  1996.     return PyInt_FromLong(cased);
  1997. }
  1998.  
  1999.  
  2000. static char istitle__doc__[] =
  2001. "S.istitle() -> int\n\
  2002. \n\
  2003. Return 1 if S is a titlecased string, i.e. uppercase characters\n\
  2004. may only follow uncased characters and lowercase characters only cased\n\
  2005. ones. Return 0 otherwise.";
  2006.  
  2007. static PyObject*
  2008. string_istitle(PyStringObject *self, PyObject *args)
  2009. {
  2010.     register const unsigned char *p = (unsigned char *) PyString_AS_STRING(self);
  2011.     register const unsigned char *e;
  2012.     int cased, previous_is_cased;
  2013.  
  2014.     if (!PyArg_NoArgs(args))
  2015.         return NULL;
  2016.  
  2017.     /* Shortcut for single character strings */
  2018.     if (PyString_GET_SIZE(self) == 1)
  2019.     return PyInt_FromLong(isupper(*p) != 0);
  2020.  
  2021.     e = p + PyString_GET_SIZE(self);
  2022.     cased = 0;
  2023.     previous_is_cased = 0;
  2024.     for (; p < e; p++) {
  2025.     register const unsigned char ch = *p;
  2026.  
  2027.     if (isupper(ch)) {
  2028.         if (previous_is_cased)
  2029.         return PyInt_FromLong(0);
  2030.         previous_is_cased = 1;
  2031.         cased = 1;
  2032.     }
  2033.     else if (islower(ch)) {
  2034.         if (!previous_is_cased)
  2035.         return PyInt_FromLong(0);
  2036.         previous_is_cased = 1;
  2037.         cased = 1;
  2038.     }
  2039.     else
  2040.         previous_is_cased = 0;
  2041.     }
  2042.     return PyInt_FromLong(cased);
  2043. }
  2044.  
  2045.  
  2046. static char splitlines__doc__[] =
  2047. "S.splitlines([keepends]]) -> list of strings\n\
  2048. \n\
  2049. Return a list of the lines in S, breaking at line boundaries.\n\
  2050. Line breaks are not included in the resulting list unless keepends\n\
  2051. is given and true.";
  2052.  
  2053. #define SPLIT_APPEND(data, left, right)                    \
  2054.     str = PyString_FromStringAndSize(data + left, right - left);    \
  2055.     if (!str)                            \
  2056.         goto onError;                        \
  2057.     if (PyList_Append(list, str)) {                    \
  2058.         Py_DECREF(str);                        \
  2059.         goto onError;                        \
  2060.     }                                \
  2061.         else                                \
  2062.             Py_DECREF(str);
  2063.  
  2064. static PyObject*
  2065. string_splitlines(PyStringObject *self, PyObject *args)
  2066. {
  2067.     register int i;
  2068.     register int j;
  2069.     int len;
  2070.     int keepends = 0;
  2071.     PyObject *list;
  2072.     PyObject *str;
  2073.     char *data;
  2074.  
  2075.     if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
  2076.         return NULL;
  2077.  
  2078.     data = PyString_AS_STRING(self);
  2079.     len = PyString_GET_SIZE(self);
  2080.  
  2081.     list = PyList_New(0);
  2082.     if (!list)
  2083.         goto onError;
  2084.  
  2085.     for (i = j = 0; i < len; ) {
  2086.     int eol;
  2087.  
  2088.     /* Find a line and append it */
  2089.     while (i < len && data[i] != '\n' && data[i] != '\r')
  2090.         i++;
  2091.  
  2092.     /* Skip the line break reading CRLF as one line break */
  2093.     eol = i;
  2094.     if (i < len) {
  2095.         if (data[i] == '\r' && i + 1 < len &&
  2096.         data[i+1] == '\n')
  2097.         i += 2;
  2098.         else
  2099.         i++;
  2100.         if (keepends)
  2101.         eol = i;
  2102.     }
  2103.     SPLIT_APPEND(data, j, eol);
  2104.     j = i;
  2105.     }
  2106.     if (j < len) {
  2107.     SPLIT_APPEND(data, j, len);
  2108.     }
  2109.  
  2110.     return list;
  2111.  
  2112.  onError:
  2113.     Py_DECREF(list);
  2114.     return NULL;
  2115. }
  2116.  
  2117. #undef SPLIT_APPEND
  2118.  
  2119.  
  2120. static PyMethodDef 
  2121. string_methods[] = {
  2122.     /* Counterparts of the obsolete stropmodule functions; except
  2123.        string.maketrans(). */
  2124.     {"join",       (PyCFunction)string_join,       1, join__doc__},
  2125.     {"split",       (PyCFunction)string_split,       1, split__doc__},
  2126.     {"lower",      (PyCFunction)string_lower,      1, lower__doc__},
  2127.     {"upper",       (PyCFunction)string_upper,       1, upper__doc__},
  2128.     {"islower", (PyCFunction)string_islower, 0, islower__doc__},
  2129.     {"isupper", (PyCFunction)string_isupper, 0, isupper__doc__},
  2130.     {"isspace", (PyCFunction)string_isspace, 0, isspace__doc__},
  2131.     {"isdigit", (PyCFunction)string_isdigit, 0, isdigit__doc__},
  2132.     {"istitle", (PyCFunction)string_istitle, 0, istitle__doc__},
  2133.     {"capitalize", (PyCFunction)string_capitalize, 1, capitalize__doc__},
  2134.     {"count",      (PyCFunction)string_count,      1, count__doc__},
  2135.     {"endswith",   (PyCFunction)string_endswith,   1, endswith__doc__},
  2136.     {"find",       (PyCFunction)string_find,       1, find__doc__},
  2137.     {"index",      (PyCFunction)string_index,      1, index__doc__},
  2138.     {"lstrip",     (PyCFunction)string_lstrip,     1, lstrip__doc__},
  2139.     {"replace",     (PyCFunction)string_replace,     1, replace__doc__},
  2140.     {"rfind",       (PyCFunction)string_rfind,       1, rfind__doc__},
  2141.     {"rindex",      (PyCFunction)string_rindex,      1, rindex__doc__},
  2142.     {"rstrip",      (PyCFunction)string_rstrip,      1, rstrip__doc__},
  2143.     {"startswith",  (PyCFunction)string_startswith,  1, startswith__doc__},
  2144.     {"strip",       (PyCFunction)string_strip,       1, strip__doc__},
  2145.     {"swapcase",    (PyCFunction)string_swapcase,    1, swapcase__doc__},
  2146.     {"translate",   (PyCFunction)string_translate,   1, translate__doc__},
  2147.     {"title",       (PyCFunction)string_title,       1, title__doc__},
  2148.     {"ljust",       (PyCFunction)string_ljust,       1, ljust__doc__},
  2149.     {"rjust",       (PyCFunction)string_rjust,       1, rjust__doc__},
  2150.     {"center",      (PyCFunction)string_center,      1, center__doc__},
  2151.     {"expandtabs",  (PyCFunction)string_expandtabs,  1, expandtabs__doc__},
  2152.     {"splitlines",  (PyCFunction)string_splitlines,  1, splitlines__doc__},
  2153. #if 0
  2154.     {"zfill",       (PyCFunction)string_zfill,       1, zfill__doc__},
  2155. #endif
  2156.     {NULL,     NULL}             /* sentinel */
  2157. };
  2158.  
  2159. static PyObject *
  2160. string_getattr(s, name)
  2161.     PyStringObject *s;
  2162.     char *name;
  2163. {
  2164.     return Py_FindMethod(string_methods, (PyObject*)s, name);
  2165. }
  2166.  
  2167.  
  2168. PyTypeObject PyString_Type = {
  2169.     PyObject_HEAD_INIT(&PyType_Type)
  2170.     0,
  2171.     "string",
  2172.     sizeof(PyStringObject),
  2173.     sizeof(char),
  2174.     (destructor)string_dealloc, /*tp_dealloc*/
  2175.     (printfunc)string_print, /*tp_print*/
  2176.     (getattrfunc)string_getattr,        /*tp_getattr*/
  2177.     0,        /*tp_setattr*/
  2178.     (cmpfunc)string_compare, /*tp_compare*/
  2179.     (reprfunc)string_repr, /*tp_repr*/
  2180.     0,        /*tp_as_number*/
  2181.     &string_as_sequence,    /*tp_as_sequence*/
  2182.     0,        /*tp_as_mapping*/
  2183.     (hashfunc)string_hash, /*tp_hash*/
  2184.     0,        /*tp_call*/
  2185.     0,        /*tp_str*/
  2186.     0,        /*tp_getattro*/
  2187.     0,        /*tp_setattro*/
  2188.     &string_as_buffer,    /*tp_as_buffer*/
  2189.     Py_TPFLAGS_DEFAULT,    /*tp_flags*/
  2190.     0,        /*tp_doc*/
  2191. };
  2192.  
  2193. void
  2194. PyString_Concat(pv, w)
  2195.     register PyObject **pv;
  2196.     register PyObject *w;
  2197. {
  2198.     register PyObject *v;
  2199.     if (*pv == NULL)
  2200.         return;
  2201.     if (w == NULL || !PyString_Check(*pv)) {
  2202.         Py_DECREF(*pv);
  2203.         *pv = NULL;
  2204.         return;
  2205.     }
  2206.     v = string_concat((PyStringObject *) *pv, w);
  2207.     Py_DECREF(*pv);
  2208.     *pv = v;
  2209. }
  2210.  
  2211. void
  2212. PyString_ConcatAndDel(pv, w)
  2213.     register PyObject **pv;
  2214.     register PyObject *w;
  2215. {
  2216.     PyString_Concat(pv, w);
  2217.     Py_XDECREF(w);
  2218. }
  2219.  
  2220.  
  2221. /* The following function breaks the notion that strings are immutable:
  2222.    it changes the size of a string.  We get away with this only if there
  2223.    is only one module referencing the object.  You can also think of it
  2224.    as creating a new string object and destroying the old one, only
  2225.    more efficiently.  In any case, don't use this if the string may
  2226.    already be known to some other part of the code... */
  2227.  
  2228. int
  2229. _PyString_Resize(pv, newsize)
  2230.     PyObject **pv;
  2231.     int newsize;
  2232. {
  2233.     register PyObject *v;
  2234.     register PyStringObject *sv;
  2235.     v = *pv;
  2236.     if (!PyString_Check(v) || v->ob_refcnt != 1) {
  2237.         *pv = 0;
  2238.         Py_DECREF(v);
  2239.         PyErr_BadInternalCall();
  2240.         return -1;
  2241.     }
  2242.     /* XXX UNREF/NEWREF interface should be more symmetrical */
  2243. #ifdef Py_REF_DEBUG
  2244.     --_Py_RefTotal;
  2245. #endif
  2246.     _Py_ForgetReference(v);
  2247.     *pv = (PyObject *)
  2248.         PyObject_REALLOC((char *)v,
  2249.             sizeof(PyStringObject) + newsize * sizeof(char));
  2250.     if (*pv == NULL) {
  2251.         PyObject_DEL(v);
  2252.         PyErr_NoMemory();
  2253.         return -1;
  2254.     }
  2255.     _Py_NewReference(*pv);
  2256.     sv = (PyStringObject *) *pv;
  2257.     sv->ob_size = newsize;
  2258.     sv->ob_sval[newsize] = '\0';
  2259.     return 0;
  2260. }
  2261.  
  2262. /* Helpers for formatstring */
  2263.  
  2264. static PyObject *
  2265. getnextarg(args, arglen, p_argidx)
  2266.     PyObject *args;
  2267.     int arglen;
  2268.     int *p_argidx;
  2269. {
  2270.     int argidx = *p_argidx;
  2271.     if (argidx < arglen) {
  2272.         (*p_argidx)++;
  2273.         if (arglen < 0)
  2274.             return args;
  2275.         else
  2276.             return PyTuple_GetItem(args, argidx);
  2277.     }
  2278.     PyErr_SetString(PyExc_TypeError,
  2279.             "not enough arguments for format string");
  2280.     return NULL;
  2281. }
  2282.  
  2283. #define F_LJUST (1<<0)
  2284. #define F_SIGN    (1<<1)
  2285. #define F_BLANK (1<<2)
  2286. #define F_ALT    (1<<3)
  2287. #define F_ZERO    (1<<4)
  2288.  
  2289. static int
  2290. formatfloat(buf, flags, prec, type, v)
  2291.     char *buf;
  2292.     int flags;
  2293.     int prec;
  2294.     int type;
  2295.     PyObject *v;
  2296. {
  2297.     char fmt[20];
  2298.     double x;
  2299.     if (!PyArg_Parse(v, "d;float argument required", &x))
  2300.         return -1;
  2301.     if (prec < 0)
  2302.         prec = 6;
  2303.     if (prec > 50)
  2304.         prec = 50; /* Arbitrary limitation */
  2305.     if (type == 'f' && fabs(x)/1e25 >= 1e25)
  2306.         type = 'g';
  2307.     sprintf(fmt, "%%%s.%d%c", (flags&F_ALT) ? "#" : "", prec, type);
  2308.     sprintf(buf, fmt, x);
  2309.     return strlen(buf);
  2310. }
  2311.  
  2312. static int
  2313. formatint(buf, flags, prec, type, v)
  2314.     char *buf;
  2315.     int flags;
  2316.     int prec;
  2317.     int type;
  2318.     PyObject *v;
  2319. {
  2320.     char fmt[20];
  2321.     long x;
  2322.     if (!PyArg_Parse(v, "l;int argument required", &x))
  2323.         return -1;
  2324.     if (prec < 0)
  2325.         prec = 1;
  2326.     sprintf(fmt, "%%%s.%dl%c", (flags&F_ALT) ? "#" : "", prec, type);
  2327.     sprintf(buf, fmt, x);
  2328.     return strlen(buf);
  2329. }
  2330.  
  2331. static int
  2332. formatchar(buf, v)
  2333.     char *buf;
  2334.     PyObject *v;
  2335. {
  2336.     if (PyString_Check(v)) {
  2337.         if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
  2338.             return -1;
  2339.     }
  2340.     else {
  2341.         if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
  2342.             return -1;
  2343.     }
  2344.     buf[1] = '\0';
  2345.     return 1;
  2346. }
  2347.  
  2348.  
  2349. /* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...) */
  2350.  
  2351. PyObject *
  2352. PyString_Format(format, args)
  2353.     PyObject *format;
  2354.     PyObject *args;
  2355. {
  2356.     char *fmt, *res;
  2357.     int fmtcnt, rescnt, reslen, arglen, argidx;
  2358.     int args_owned = 0;
  2359.     PyObject *result, *orig_args;
  2360.     PyObject *dict = NULL;
  2361.     if (format == NULL || !PyString_Check(format) || args == NULL) {
  2362.         PyErr_BadInternalCall();
  2363.         return NULL;
  2364.     }
  2365.     orig_args = args;
  2366.     fmt = PyString_AsString(format);
  2367.     fmtcnt = PyString_Size(format);
  2368.     reslen = rescnt = fmtcnt + 100;
  2369.     result = PyString_FromStringAndSize((char *)NULL, reslen);
  2370.     if (result == NULL)
  2371.         return NULL;
  2372.     res = PyString_AsString(result);
  2373.     if (PyTuple_Check(args)) {
  2374.         arglen = PyTuple_Size(args);
  2375.         argidx = 0;
  2376.     }
  2377.     else {
  2378.         arglen = -1;
  2379.         argidx = -2;
  2380.     }
  2381.     if (args->ob_type->tp_as_mapping)
  2382.         dict = args;
  2383.     while (--fmtcnt >= 0) {
  2384.         if (*fmt != '%') {
  2385.             if (--rescnt < 0) {
  2386.                 rescnt = fmtcnt + 100;
  2387.                 reslen += rescnt;
  2388.                 if (_PyString_Resize(&result, reslen) < 0)
  2389.                     return NULL;
  2390.                 res = PyString_AsString(result)
  2391.                     + reslen - rescnt;
  2392.                 --rescnt;
  2393.             }
  2394.             *res++ = *fmt++;
  2395.         }
  2396.         else {
  2397.             /* Got a format specifier */
  2398.             int flags = 0;
  2399.             int width = -1;
  2400.             int prec = -1;
  2401.             int size = 0;
  2402.             int c = '\0';
  2403.             int fill;
  2404.             PyObject *v = NULL;
  2405.             PyObject *temp = NULL;
  2406.             char *buf;
  2407.             int sign;
  2408.             int len;
  2409.             char tmpbuf[120]; /* For format{float,int,char}() */
  2410.             char *fmt_start = fmt;
  2411.             
  2412.             fmt++;
  2413.             if (*fmt == '(') {
  2414.                 char *keystart;
  2415.                 int keylen;
  2416.                 PyObject *key;
  2417.                 int pcount = 1;
  2418.  
  2419.                 if (dict == NULL) {
  2420.                     PyErr_SetString(PyExc_TypeError,
  2421.                          "format requires a mapping"); 
  2422.                     goto error;
  2423.                 }
  2424.                 ++fmt;
  2425.                 --fmtcnt;
  2426.                 keystart = fmt;
  2427.                 /* Skip over balanced parentheses */
  2428.                 while (pcount > 0 && --fmtcnt >= 0) {
  2429.                     if (*fmt == ')')
  2430.                         --pcount;
  2431.                     else if (*fmt == '(')
  2432.                         ++pcount;
  2433.                     fmt++;
  2434.                 }
  2435.                 keylen = fmt - keystart - 1;
  2436.                 if (fmtcnt < 0 || pcount > 0) {
  2437.                     PyErr_SetString(PyExc_ValueError,
  2438.                            "incomplete format key");
  2439.                     goto error;
  2440.                 }
  2441.                 key = PyString_FromStringAndSize(keystart,
  2442.                                  keylen);
  2443.                 if (key == NULL)
  2444.                     goto error;
  2445.                 if (args_owned) {
  2446.                     Py_DECREF(args);
  2447.                     args_owned = 0;
  2448.                 }
  2449.                 args = PyObject_GetItem(dict, key);
  2450.                 Py_DECREF(key);
  2451.                 if (args == NULL) {
  2452.                     goto error;
  2453.                 }
  2454.                 args_owned = 1;
  2455.                 arglen = -1;
  2456.                 argidx = -2;
  2457.             }
  2458.             while (--fmtcnt >= 0) {
  2459.                 switch (c = *fmt++) {
  2460.                 case '-': flags |= F_LJUST; continue;
  2461.                 case '+': flags |= F_SIGN; continue;
  2462.                 case ' ': flags |= F_BLANK; continue;
  2463.                 case '#': flags |= F_ALT; continue;
  2464.                 case '0': flags |= F_ZERO; continue;
  2465.                 }
  2466.                 break;
  2467.             }
  2468.             if (c == '*') {
  2469.                 v = getnextarg(args, arglen, &argidx);
  2470.                 if (v == NULL)
  2471.                     goto error;
  2472.                 if (!PyInt_Check(v)) {
  2473.                     PyErr_SetString(PyExc_TypeError,
  2474.                             "* wants int");
  2475.                     goto error;
  2476.                 }
  2477.                 width = PyInt_AsLong(v);
  2478.                 if (width < 0) {
  2479.                     flags |= F_LJUST;
  2480.                     width = -width;
  2481.                 }
  2482.                 if (--fmtcnt >= 0)
  2483.                     c = *fmt++;
  2484.             }
  2485.             else if (c >= 0 && isdigit(c)) {
  2486.                 width = c - '0';
  2487.                 while (--fmtcnt >= 0) {
  2488.                     c = Py_CHARMASK(*fmt++);
  2489.                     if (!isdigit(c))
  2490.                         break;
  2491.                     if ((width*10) / 10 != width) {
  2492.                         PyErr_SetString(
  2493.                             PyExc_ValueError,
  2494.                             "width too big");
  2495.                         goto error;
  2496.                     }
  2497.                     width = width*10 + (c - '0');
  2498.                 }
  2499.             }
  2500.             if (c == '.') {
  2501.                 prec = 0;
  2502.                 if (--fmtcnt >= 0)
  2503.                     c = *fmt++;
  2504.                 if (c == '*') {
  2505.                     v = getnextarg(args, arglen, &argidx);
  2506.                     if (v == NULL)
  2507.                         goto error;
  2508.                     if (!PyInt_Check(v)) {
  2509.                         PyErr_SetString(
  2510.                             PyExc_TypeError,
  2511.                             "* wants int");
  2512.                         goto error;
  2513.                     }
  2514.                     prec = PyInt_AsLong(v);
  2515.                     if (prec < 0)
  2516.                         prec = 0;
  2517.                     if (--fmtcnt >= 0)
  2518.                         c = *fmt++;
  2519.                 }
  2520.                 else if (c >= 0 && isdigit(c)) {
  2521.                     prec = c - '0';
  2522.                     while (--fmtcnt >= 0) {
  2523.                         c = Py_CHARMASK(*fmt++);
  2524.                         if (!isdigit(c))
  2525.                             break;
  2526.                         if ((prec*10) / 10 != prec) {
  2527.                             PyErr_SetString(
  2528.                                 PyExc_ValueError,
  2529.                                 "prec too big");
  2530.                             goto error;
  2531.                         }
  2532.                         prec = prec*10 + (c - '0');
  2533.                     }
  2534.                 }
  2535.             } /* prec */
  2536.             if (fmtcnt >= 0) {
  2537.                 if (c == 'h' || c == 'l' || c == 'L') {
  2538.                     size = c;
  2539.                     if (--fmtcnt >= 0)
  2540.                         c = *fmt++;
  2541.                 }
  2542.             }
  2543.             if (fmtcnt < 0) {
  2544.                 PyErr_SetString(PyExc_ValueError,
  2545.                         "incomplete format");
  2546.                 goto error;
  2547.             }
  2548.             if (c != '%') {
  2549.                 v = getnextarg(args, arglen, &argidx);
  2550.                 if (v == NULL)
  2551.                     goto error;
  2552.             }
  2553.             sign = 0;
  2554.             fill = ' ';
  2555.             switch (c) {
  2556.             case '%':
  2557.                 buf = "%";
  2558.                 len = 1;
  2559.                 break;
  2560.             case 's':
  2561.               case 'r':
  2562.                 if (PyUnicode_Check(v)) {
  2563.                     fmt = fmt_start;
  2564.                     goto unicode;
  2565.                 }
  2566.                 if (c == 's')
  2567.                 temp = PyObject_Str(v);
  2568.                 else
  2569.                     temp = PyObject_Repr(v);
  2570.                 if (temp == NULL)
  2571.                     goto error;
  2572.                 if (!PyString_Check(temp)) {
  2573.                     PyErr_SetString(PyExc_TypeError,
  2574.                       "%s argument has non-string str()");
  2575.                     goto error;
  2576.                 }
  2577.                 buf = PyString_AsString(temp);
  2578.                 len = PyString_Size(temp);
  2579.                 if (prec >= 0 && len > prec)
  2580.                     len = prec;
  2581.                 break;
  2582.             case 'i':
  2583.             case 'd':
  2584.             case 'u':
  2585.             case 'o':
  2586.             case 'x':
  2587.             case 'X':
  2588.                 if (c == 'i')
  2589.                     c = 'd';
  2590.                 buf = tmpbuf;
  2591.                 len = formatint(buf, flags, prec, c, v);
  2592.                 if (len < 0)
  2593.                     goto error;
  2594.                 sign = (c == 'd');
  2595.                 if (flags&F_ZERO) {
  2596.                     fill = '0';
  2597.                     if ((flags&F_ALT) &&
  2598.                         (c == 'x' || c == 'X') &&
  2599.                         buf[0] == '0' && buf[1] == c) {
  2600.                         *res++ = *buf++;
  2601.                         *res++ = *buf++;
  2602.                         rescnt -= 2;
  2603.                         len -= 2;
  2604.                         width -= 2;
  2605.                         if (width < 0)
  2606.                             width = 0;
  2607.                     }
  2608.                 }
  2609.                 break;
  2610.             case 'e':
  2611.             case 'E':
  2612.             case 'f':
  2613.             case 'g':
  2614.             case 'G':
  2615.                 buf = tmpbuf;
  2616.                 len = formatfloat(buf, flags, prec, c, v);
  2617.                 if (len < 0)
  2618.                     goto error;
  2619.                 sign = 1;
  2620.                 if (flags&F_ZERO)
  2621.                     fill = '0';
  2622.                 break;
  2623.             case 'c':
  2624.                 buf = tmpbuf;
  2625.                 len = formatchar(buf, v);
  2626.                 if (len < 0)
  2627.                     goto error;
  2628.                 break;
  2629.             default:
  2630.                 PyErr_Format(PyExc_ValueError,
  2631.                 "unsupported format character '%c' (0x%x)",
  2632.                     c, c);
  2633.                 goto error;
  2634.             }
  2635.             if (sign) {
  2636.                 if (*buf == '-' || *buf == '+') {
  2637.                     sign = *buf++;
  2638.                     len--;
  2639.                 }
  2640.                 else if (flags & F_SIGN)
  2641.                     sign = '+';
  2642.                 else if (flags & F_BLANK)
  2643.                     sign = ' ';
  2644.                 else
  2645.                     sign = '\0';
  2646.             }
  2647.             if (width < len)
  2648.                 width = len;
  2649.             if (rescnt < width + (sign != '\0')) {
  2650.                 reslen -= rescnt;
  2651.                 rescnt = width + fmtcnt + 100;
  2652.                 reslen += rescnt;
  2653.                 if (_PyString_Resize(&result, reslen) < 0)
  2654.                     return NULL;
  2655.                 res = PyString_AsString(result)
  2656.                     + reslen - rescnt;
  2657.             }
  2658.             if (sign) {
  2659.                 if (fill != ' ')
  2660.                     *res++ = sign;
  2661.                 rescnt--;
  2662.                 if (width > len)
  2663.                     width--;
  2664.             }
  2665.             if (width > len && !(flags&F_LJUST)) {
  2666.                 do {
  2667.                     --rescnt;
  2668.                     *res++ = fill;
  2669.                 } while (--width > len);
  2670.             }
  2671.             if (sign && fill == ' ')
  2672.                 *res++ = sign;
  2673.             memcpy(res, buf, len);
  2674.             res += len;
  2675.             rescnt -= len;
  2676.             while (--width >= len) {
  2677.                 --rescnt;
  2678.                 *res++ = ' ';
  2679.             }
  2680.                         if (dict && (argidx < arglen) && c != '%') {
  2681.                                 PyErr_SetString(PyExc_TypeError,
  2682.                                            "not all arguments converted");
  2683.                                 goto error;
  2684.                         }
  2685.             Py_XDECREF(temp);
  2686.         } /* '%' */
  2687.     } /* until end */
  2688.     if (argidx < arglen && !dict) {
  2689.         PyErr_SetString(PyExc_TypeError,
  2690.                 "not all arguments converted");
  2691.         goto error;
  2692.     }
  2693.     if (args_owned) {
  2694.         Py_DECREF(args);
  2695.     }
  2696.     _PyString_Resize(&result, reslen - rescnt);
  2697.     return result;
  2698.  
  2699.  unicode:
  2700.     if (args_owned) {
  2701.         Py_DECREF(args);
  2702.         args_owned = 0;
  2703.     }
  2704.     /* Fiddle args right (remove the first argidx-1 arguments) */
  2705.     --argidx;
  2706.     if (PyTuple_Check(orig_args) && argidx > 0) {
  2707.         PyObject *v;
  2708.         int n = PyTuple_GET_SIZE(orig_args) - argidx;
  2709.         v = PyTuple_New(n);
  2710.         if (v == NULL)
  2711.             goto error;
  2712.         while (--n >= 0) {
  2713.             PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
  2714.             Py_INCREF(w);
  2715.             PyTuple_SET_ITEM(v, n, w);
  2716.         }
  2717.         args = v;
  2718.     } else {
  2719.         Py_INCREF(orig_args);
  2720.         args = orig_args;
  2721.     }
  2722.     /* Paste rest of format string to what we have of the result
  2723.        string; we reuse result for this */
  2724.     rescnt = res - PyString_AS_STRING(result);
  2725.     fmtcnt = PyString_GET_SIZE(format) - \
  2726.          (fmt - PyString_AS_STRING(format));
  2727.     if (_PyString_Resize(&result, rescnt + fmtcnt)) {
  2728.         Py_DECREF(args);
  2729.         goto error;
  2730.     }
  2731.     memcpy(PyString_AS_STRING(result) + rescnt, fmt, fmtcnt);
  2732.     format = result;
  2733.     /* Let Unicode do its magic */
  2734.     result = PyUnicode_Format(format, args);
  2735.     Py_DECREF(format);
  2736.     Py_DECREF(args);
  2737.     return result;
  2738.     
  2739.  error:
  2740.     Py_DECREF(result);
  2741.     if (args_owned) {
  2742.         Py_DECREF(args);
  2743.     }
  2744.     return NULL;
  2745. }
  2746.  
  2747.  
  2748. #ifdef INTERN_STRINGS
  2749.  
  2750. static PyObject *interned;
  2751.  
  2752. void
  2753. PyString_InternInPlace(p)
  2754.     PyObject **p;
  2755. {
  2756.     register PyStringObject *s = (PyStringObject *)(*p);
  2757.     PyObject *t;
  2758.     if (s == NULL || !PyString_Check(s))
  2759.         Py_FatalError("PyString_InternInPlace: strings only please!");
  2760.     if ((t = s->ob_sinterned) != NULL) {
  2761.         if (t == (PyObject *)s)
  2762.             return;
  2763.         Py_INCREF(t);
  2764.         *p = t;
  2765.         Py_DECREF(s);
  2766.         return;
  2767.     }
  2768.     if (interned == NULL) {
  2769.         interned = PyDict_New();
  2770.         if (interned == NULL)
  2771.             return;
  2772.     }
  2773.     if ((t = PyDict_GetItem(interned, (PyObject *)s)) != NULL) {
  2774.         Py_INCREF(t);
  2775.         *p = s->ob_sinterned = t;
  2776.         Py_DECREF(s);
  2777.         return;
  2778.     }
  2779.     t = (PyObject *)s;
  2780.     if (PyDict_SetItem(interned, t, t) == 0) {
  2781.         s->ob_sinterned = t;
  2782.         return;
  2783.     }
  2784.     PyErr_Clear();
  2785. }
  2786.  
  2787.  
  2788. PyObject *
  2789. PyString_InternFromString(cp)
  2790.     const char *cp;
  2791. {
  2792.     PyObject *s = PyString_FromString(cp);
  2793.     if (s == NULL)
  2794.         return NULL;
  2795.     PyString_InternInPlace(&s);
  2796.     return s;
  2797. }
  2798.  
  2799. #endif
  2800.  
  2801. void
  2802. PyString_Fini()
  2803. {
  2804.     int i;
  2805.     for (i = 0; i < UCHAR_MAX + 1; i++) {
  2806.         Py_XDECREF(characters[i]);
  2807.         characters[i] = NULL;
  2808.     }
  2809. #ifndef DONT_SHARE_SHORT_STRINGS
  2810.     Py_XDECREF(nullstring);
  2811.     nullstring = NULL;
  2812. #endif
  2813. #ifdef INTERN_STRINGS
  2814.     if (interned) {
  2815.         int pos, changed;
  2816.         PyObject *key, *value;
  2817.         do {
  2818.             changed = 0;
  2819.             pos = 0;
  2820.             while (PyDict_Next(interned, &pos, &key, &value)) {
  2821.                 if (key->ob_refcnt == 2 && key == value) {
  2822.                     PyDict_DelItem(interned, key);
  2823.                     changed = 1;
  2824.                 }
  2825.             }
  2826.         } while (changed);
  2827.     }
  2828. #endif
  2829. }
  2830.